<?php
/**
 * DMFramework
 * 
 * @license Copyright 2012 Dillen Meijboom under the Apache license version 2.0 (http://apache.org/licenses/LICENSE-2.0)
 * @author Dillen Meijboom <info@dillenm.nl>
 * @url http://dmframework.nl
 */

/**
 * This is an anonymous class which has a few more methods then the stdClass
 * 
 * @license Copyright 2012 Dillen Meijboom under the Apache license version 2.0 (http://apache.org/licenses/LICENSE-2.0)
 * @author Dillen Meijboom <info@dillenm.nl>
 * @package System.Core
 */
class Dmf_Stdclass extends stdClass
{
    /**
     * Return as array
     * 
     * @return array 
     */
    public function asArray()
    {
        return (array)$this;
    }
    
    /**
     * With this method you can add methods on the fly
     *  
     * @param string $method
     * @param array $args
     * @return mixed 
     */
    public function __call( $method_name, $args )
    {
        $method = $this->$method_name;
        
        if ( isset( $this->$method_name ) )
        {
            if ( count( $args ) > 0 )
            {
                return $method( $this, $args ); 
            }
            else
            {
                return $method( $this );
            }
        }
    }
    
    /**
     * Create Stdclass from array
     * 
     * @param array $array 
     */
    public static function fromArray( $array )
    {
        $obj = new Dmf_Stdclass;
        
        foreach( $array as $key => $val )
        {
            if ( is_array( $val ) )
            {
                $obj->$key = Dmf_Stdclass::fromArray( $val );
                continue;
            }
            
            $obj->$key = $val;
        }
        
        return $obj;
    }
    
    /**
     * The toString method 
     */
    public function __toString()
    {
        if ( isset( $this->value ) )
        {
            return (string)$this->value;
        }
    }
}